﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace _5___StringInFiles
{
    class Program
    {
        private static void Traverse(string path, string searchString)
        {
            string[] subdirs = Directory.GetDirectories(path);
            foreach (string subdir in subdirs)
            {
                Traverse(subdir, searchString);
            }
            string[] files = Directory.GetFiles(path);
            foreach (string f in files)
            {
                StreamWriter writer = new StreamWriter("result.txt", true);
                using (writer)
                {
                    Console.WriteLine(f);
                    FileInfo file = new FileInfo(f);
                    if (file.Extension == ".txt")
                    {
                        string line = SearchFile(f, searchString);
                        if (line != "nomatch")
                        {
                            writer.WriteLine(f);
                            writer.WriteLine(line);
                            writer.WriteLine();
                        }
                    }
                }
            }
        }

        private static string SearchFile(string path, string searchString)
        {
            StreamReader reader = new StreamReader(path);
            using (reader)
            {
                string f = reader.ReadLine();
                while (f != null)
                {
                    int x = f.IndexOf(searchString);
                    if (x > -1)
                        return f;
                    f = reader.ReadLine();
                }
            }
            return "nomatch";
        }

        static void Main(string[] args)
        {
            string startingFolder = @"C:\Users\Academy\Documents\Visual Studio 2008";
            string searchString = "key";
            Traverse(startingFolder, searchString);
        }
    }
}
